package com.ctrip.payment.service;

import com.ckjava.xutils.HttpClientUtils;
import com.ckjava.xutils.http.HttpResult;
import com.ctrip.payment.domain.Task;
import com.ctrip.payment.service.base.BaseJpaCrudService;
import com.ctrip.payment.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class TaskService extends BaseJpaCrudService<Task> {

    private static Logger logger = LoggerFactory.getLogger(BaseJpaCrudService.class);

    @Override
    public Class<Task> getClassType() {
        return Task.class;
    }

    /**
     * 从 api 获取 Task 对象
     *
     * @param name
     * @return
     */
    public Task loadTaskFromApi(String name) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("name", name);
            HttpResult httpResult = HttpClientUtils.get("http://ps.task.com/api", null, params);
            if (httpResult.getStatusCode() == 200) {
                return JsonUtils.getMapper().readValue(httpResult.getBodyString(), Task.class);
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error(String.format("has error"), e);
            return null;
        }

    }

}
